#!/bin/bash


#if [ $HOME == "/root" ];then
#	echo -e  "\e[0;31mplease run with sudo\e[0m"
#	exit
#fi

export `cat ./envlist`

id=`id -u $USER`
name="$USER"
rootfs="./rootfs"

declare -a bindlist envlist

bindlist+=("--types proc"  "/proc                      "  "$rootfs/proc                      ")
bindlist+=("-B          "  "/sys                       "  "$rootfs/sys                       ")
bindlist+=("-B          "  "/dev                       "  "$rootfs/dev                       ")
bindlist+=("-Brw        "  "/tmp                       "  "$rootfs/tmp                       ")
bindlist+=("-B          "  "/run/user/$id/pulse        "  "$rootfs/run/user/$id/pulse        ")
bindlist+=("-B          "  "/run/dbus/system_bus_socket"  "$rootfs/run/dbus/system_bus_socket")
bindlist+=("-Br         "  "$HOME/.themes              "  "$rootfs/home/$name/.themes        ")
bindlist+=("-Br         "  "$HOME/.icons               "  "$rootfs/home/$name/.icons         ")
bindlist+=("-Br         "  "$HOME/.fonts               "  "$rootfs/home/$name/.fonts         ")
bindlist+=("-Br         "  "$HOME/.gtkrc-2.0           "  "$rootfs/home/$name/.gtkrc-2.0     ")
bindlist+=("-Br         "  "$HOME/.config/gtk-2.0      "  "$rootfs/home/$name/.config/gtk-2.0")
bindlist+=("-Br         "  "$HOME/.config/gtk-3.0      "  "$rootfs/home/$name/.config/gtk-3.0")

envlist+=("DISPLAY=$DISPLAY")
envlist+=("XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR")
envlist+=("DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS")


function init_rootfs(){
	# 解压tar包
	tar xpvf rootfs.tar.xz --xattrs-include='*.*' --numeric-owner --directory=$rootfs

	# 挂载文件系统
	mount --types proc /proc $rootfs/proc
	mount --rbind /sys $rootfs/sys
	mount --make-rslave $rootfs/sys
	mount --rbind /dev $rootfs/dev
	mount --make-rslave $rootfs/dev
	mount --bind /run $rootfs/run
	mount --make-slave $rootfs/run

	# 复制 dns 配置
	rm $rootfs/etc/resolv.conf &> /dev/null
	cp -f /etc/resolv.conf $rootfs/etc/

	# 复制 machine-id，dbus 或其他程序会需要
	cp -f /etc/machine-id $rootfs/etc/

	# 时区设置
	chroot $rootfs ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
	echo "LANG=en_US.UTF-8" >> $rootfs/etc/locale.conf
	echo "en_US.UTF-8 UTF-8" >> $rootfs/etc/locale.gen
	chroot $rootfs locale-gen

	# 创建用户
	chroot $rootfs useradd -m -s /bin/bash -u $id $name
	chown -R $id:$id $rootfs/home/$name


	# 添加 multilib 32 位仓库，修改为清华软件源
	echo -e "[multilib]\nInclude = /etc/pacman.d/mirrorlist" >> $rootfs/etc/pacman.conf
	echo "Server = https://mirror.sjtu.edu.cn/archlinux/\$repo/os/\$arch" > $rootfs/etc/pacman.d/mirrorlist

	# 安装基本工具
	chroot $rootfs pacman -Syu --noconfirm base-devel git

	# 配置 sudo
	echo "$name ALL=(ALL) NOPASSWD: ALL" >> $rootfs/etc/sudoers
	echo "MAKEFLAGS=j16" >> $rootfs/etc/makepkg.conf
}



function mountlist(){
	for i in $(seq 0 3 $((${#bindlist[@]}-3))); do
		param=${bindlist[$i]}
		origin=${bindlist[$((i+1))]}
		mountpoint=${bindlist[$((i+2))]}
		if [ -f $origin ]; then
			if [ ! -f $mountpoint ]; then
				echo -e  "\e[0;32mcreate mountpoint: $mountpoint\e[0m"
				install -D /dev/null $mountpoint
			fi
		elif [ -S $origin ]; then
			if [ ! -S $mountpoint ]; then
				echo -e  "\e[0;32mcreate mountpoint: $mountpoint\e[0m"
				install -D /dev/null $mountpoint
			fi
		elif [ -d $origin ]; then
			if [ ! -d $mountpoint ]; then
				echo -e  "\e[0;32mcreate mountpoint: $mountpoint\e[0m"
				install -d $mountpoint
			fi
		else
			echo -e  "\e[0;31mskip: $origin : file or directory not exist\e[0m"
			continue
		fi
		mounted=$(findmnt $mountpoint)
		if [[ -z $mounted ]];then
			echo -e  "\e[0;32mmount $param $origin $mountpoint\e[0m"
			mount $param $origin $mountpoint
		else
			echo -e  "\e[0;33mskip: $mountpoint: already mounted\e[0m"
		fi
	done
}


function umountlist(){
	for i in $(seq 2 3 $((${#bindlist[@]}))); do
		mountpoint=${bindlist[$((i))]}
		mounted=$(findmnt $mountpoint)
		if [[ -z $mounted ]];then
			echo -e  "\e[0;33mskip: $mountpoint: not mounted\e[0m"
		else
			echo -e  "\e[0;32mumount $mountpoint\e[0m"
			umount $mountpoint
		fi
	done
}


if [[ $1 == "install" ]];then
	init_rootfs
	exit
fi


if [[ $1 == "mount" ]];then
	mountlist
	exit
fi

if [[ $1 == "umount" ]];then
	umount -R ./rootfs
	exit
fi


if [[ $1 == "chroot" ]];then
	for v in ${envlist[@]}; do
		envs+="export $v;"
	done
	envs+="${envs}bash"
	echo "$envs"
	chroot $rootfs bash -c "$envs"
	exit
fi
